<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="1046px"
      title="用户配置"
      wrapClassName="user-config-modal-container"
      @cancel="closeModal()"
    >
      <div class="user-config-modal-body flex" v-loading="pageLoading">
        <div class="no-choose-container">
          <div class="transfer-header flex">
            未选人员<a-checkbox v-model="allChooseFlag" @change="allChoose()">
              全选
            </a-checkbox>
          </div>
          <div class="transfer-container flex">
            <div class="organization">
              <div class="filter-data">
                <div class="input flex" style="border: none">
                  <a-tree-select
                    allowClear
                    placeholder="请选择租户名称"
                    :replaceFields="{
                      children: 'child',
                      title: 'tenantName',
                      key: 'id',
                      value: 'tenantCode',
                    }"
                    v-model="orgName"
                    :tree-data="treeSelectSource"
                    style="width: 100%"
                    :loading="treeSelectLoading"
                    @change="tenantChange"
                  >
                  </a-tree-select>
                </div>
              </div>
              <div class="filter-result" v-loading="orgLoading">
                <a-empty :image="simpleImage" v-if="treeData.length == 0" />
                <a-tree
                  v-model="checkedKeys"
                  show-icon
                  :expanded-keys="expandedKeys"
                  :auto-expand-parent="autoExpandParent"
                  :selected-keys="selectedKeys"
                  :tree-data="treeData"
                  :replaceFields="{
                    children: 'childs',
                    title: 'orgName',
                    key: 'id',
                  }"
                  @expand="onExpand"
                  @select="onSelect"
                >
                  <template slot="custom" slot-scope="{ childs }">
                    <img
                      class="menu-icon"
                      src="@/assets/images/folder.png"
                      v-if="childs"
                    />
                    <img
                      v-else
                      class="menu-icon"
                      src="@/assets/images/file.png"
                    />
                  </template>
                </a-tree>
              </div>
            </div>
            <div class="people">
              <div class="filter-data">
                <div class="input flex">
                  <a-input
                    type="text"
                    placeholder="请输入姓名"
                    v-model.trim="userName"
                    @pressEnter="filterData()"
                  />
                  <bj-icon-font
                    type="search"
                    color="#8A8A8C"
                    :size="18"
                    @click="filterData()"
                  ></bj-icon-font>
                </div>
              </div>
              <div class="filter-result" v-loading="userListLoading">
                <a-empty :image="simpleImage" v-if="peoleOptions.length == 0" />
                <a-checkbox-group
                  v-model="people"
                  name="checkboxgroup"
                  :options="peoleOptions"
                />
              </div>
            </div>
          </div>
        </div>
        <div class="transfer-button">
          <div
            class="button"
            :class="people.length == 0 && 'dis'"
            @click="transferData()"
          ></div>
        </div>
        <div class="choose-container">
          <div class="transfer-header flex">
            已选人员 <span class="clear-all" @click="allClear()">全部清空</span>
          </div>
          <div class="transfer-container">
            <a-empty :image="simpleImage" v-if="hasChoosedUser.length == 0" />
            <div
              class="choosed-people"
              v-for="item in hasChoosedUser"
              :key="item.id"
            >
              <span>{{ item.userName }}</span>
              <span class="colose">
                <bj-icon-font
                  type="close"
                  color="#fff"
                  :size="12"
                  @click="removeUser(item)"
                ></bj-icon-font>
              </span>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer flex">
        <a-button type="default" @click="closeModal()">取消 </a-button>
        <a-button
          type="primary"
          :loading="loading"
          @click="submit()"
          :disabled="hasChoosedUser.length == 0"
        >
          提交
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import {
  queryAllOrgTreeList,
  getChoosedUser,
  insertData,
} from "@/api/user-center/roleManage.js";
import { getTenantList } from "@/api/user-center/organizationManage.js";
import { getUserManageList } from "@/api/user-center/userManage.js";
import { getLoginData } from "@/tools";
import { addAttributeByKey, flatTreeData } from "@/utils";
import _ from "lodash";
import { Empty } from "ant-design-vue";
export default {
  name: "userConfigModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      people: [],
      peoleOptions: [],
      //
      orgLoading: false,
      treeSelectSource: [],
      treeSelectLoading: false,
      orgName: undefined,
      userListLoading: false,
      orgId: "",
      orignData: [],
      userName: undefined,
      //已选人员
      hasChoosedUser: [],
      allChooseFlag: false,
      pageLoading: true,
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.pageLoading = true;
          Promise.all([
            this.queryAllOrgTreeList(),
            this.getTenantList(),
            this.getChoosedUser(),
          ]).finally((_) => {
            this.orgLoading = false;
            this.pageLoading = false;
          });
        }
      },
      immediate: true,
    },
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  mounted() {},
  methods: {
    //提交
    submit() {
      if (this.hasChoosedUser.length > 0) {
        this.loading = true;
        let ids = this.hasChoosedUser.map((v) => v.id);
        insertData({
          userIds: ids.toString(),
          roleId: this.id,
        })
          .then((res) => {
            let { data } = res;
            if (data?.result) {
              this.$message.success("操作成功");
            } else {
              this.$message.error("操作失败，请稍后重试！");
            }
            this.$parent.refreshData();
            this.closeModal();
          })
          .catch((_) => {
            this.$message.error("操作失败，请稍后重试！");
          })
          .finally((_) => {
            this.loading = false;
          });
      }
    },

    //查询已选人员
    getChoosedUser() {
      return new Promise((resolve, reject) => {
        getChoosedUser({ roleId: this.id || "" })
          .then((res) => {
            let { data } = res;
            (data?.result || []).forEach((v) => {
              let { userId, userName } = v;
              v.label = userName;
              v.value = userId;
              v.id = userId;
            });
            this.hasChoosedUser = data?.result || [];
            resolve();
          })
          .catch((_) => {
            this.hasChoosedUser = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //数据移动到右侧
    transferData() {
      let { people, peoleOptions } = this;
      if (people?.length > 0) {
        this.hasChoosedUser = this.hasChoosedUser.concat(
          peoleOptions.filter((v) => people.includes(v.value))
        );
        setTimeout(() => {
          this.disabledUserList();
          this.people = [];
          this.allChooseFlag = false;
        });
      }
    },

    //单个删除已选数据
    removeUser(item) {
      let { id } = item;
      this.peoleOptions.forEach((v) => {
        if (v.id == id) {
          this.$set(v, "disabled", false);
        }
      });
      this.orignData.forEach((v) => {
        if (v.id == id) {
          this.$set(v, "disabled", false);
        }
      });
      this.hasChoosedUser = this.hasChoosedUser.filter((v) => v.value != id);
    },

    //禁用人员列表
    disabledUserList() {
      let ids = this.hasChoosedUser.map((v) => v.id);
      this.peoleOptions.forEach((v) => {
        this.$set(v, "disabled", ids.includes(v.value));
      });
      this.orignData.forEach((v) => {
        this.$set(v, "disabled", ids.includes(v.value));
      });
      //this.orignData = _.cloneDeep(this.peoleOptions);
    },

    //右侧全部清空
    allClear() {
      this.hasChoosedUser = [];
      this.disabledUserList();
    },

    //左侧全选
    allChoose() {
      let { allChooseFlag } = this;
      if (allChooseFlag) {
        let ids = this.hasChoosedUser.map((v) => v.id);
        this.peoleOptions.forEach((v) => {
          let { id } = v;
          if (!ids.includes(id)) {
            this.people.push(id);
          }
        });
      } else {
        this.people = [];
      }
    },

    //查询组织列表
    queryAllOrgTreeList() {
      this.orgLoading = true;
      return new Promise((resolve, reject) => {
        let { orgName } = this;
        queryAllOrgTreeList({ tenantCode: orgName || "" })
          .then((res) => {
            let { data } = res;
            this.treeData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              data?.result || [],
              "childs"
            );
            resolve();
          })
          .catch((_) => {
            this.treeData = [];
            reject();
          })
          .finally((_) => {
            this.peoleOptions = [];
            this.selectedKeys = [];
            this.expandedKeys = [];
          });
      });
    },

    //查询人员列表
    getUserManageList() {
      this.userListLoading = true;
      let { orgId } = this;
      return new Promise((resolve, reject) => {
        getUserManageList({
          page: 1,
          pageSize: -1,
          userName: "",
          userState: "",
          orgId: orgId,
        })
          .then((res) => {
            let { data } = res;
            this.peoleOptions = data?.result?.rows || [];
            this.peoleOptions.forEach((v) => {
              let { userName, id, mobile } = v;
              v.label = `${userName}(${mobile})`;
              v.value = id;
            });
            this.orignData = _.cloneDeep(this.peoleOptions);
            this.disabledUserList();
            resolve();
          })
          .catch((_) => {
            this.peoleOptions = [];
            this.orignData = [];
            reject();
          })
          .finally((_) => {
            this.userListLoading = false;
          });
      });
    },

    //查询租户列表
    getTenantList() {
      this.treeSelectLoading = true;
      return new Promise((resolve, reject) => {
        let { userId } = getLoginData();
        getTenantList({ userId })
          .then((res) => {
            let { data } = res;
            let tree = data?.result || [];
            this.treeSelectSource = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              tree,
              "child"
            );
            resolve();
          })
          .catch((_) => {
            this.treeSelectSource = [];
            reject();
          })
          .finally((_) => {
            this.treeSelectLoading = false;
          });
      });
    },

    tenantChange() {
      this.queryAllOrgTreeList().finally((_) => {
        this.orgLoading = false;
      });
    },

    //搜索
    filterData() {
      let { userName, orignData } = this;
      this.peoleOptions = orignData.filter((v) =>
        v.label.toLowerCase().includes(userName.toLowerCase())
      );
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //树选择事件
    onSelect(selectedKeys, el) {
      let { id } = el.node.dataRef;
      this.selectedKeys = [id];
      this.orgId = id;
      this.getUserManageList();
    },

    //关闭弹窗
    closeModal() {
      this.$emit("update:visible", false);
      this.selectedKeys = [];
      this.expandedKeys = [];
      this.checkedKeys = [];
      this.selectedKeys = [];
      this.treeData = [];
      this.people = [];
      this.peoleOptions = [];
      this.treeSelectSource = [];
      this.orgName = undefined;
      this.orgId = [];
      this.orignData = [];
      this.hasChoosedUser = [];
      this.userName = "";
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.user-config-modal-container {
  /deep/.ant-empty {
    margin: 0;
    height: 93%;
  }
  .ant-modal-body {
    padding: 20px 60px;
    .user-config-modal-body {
      margin-bottom: 40px;
      height: 424px;
      .transfer-header {
        width: 100%;
        height: 36px;
        background: #f3f4f6;
        color: #2b2c30;
        padding: 0 10px;
        align-items: center;
        justify-content: space-between;
        flex-shrink: 0;
        .clear-all {
          color: var(--primary-color);
          cursor: pointer;
        }
      }
      .transfer-container {
        flex: 1;
        overflow: hidden;
        .organization,
        .people {
          height: 100%;
          width: 350px;
          .flex();
          flex-direction: column;
          overflow: hidden;
          .filter-data {
            padding: 10px;
            flex-shrink: 0;
            .input {
              height: 36px;
              background: #ffffff;
              border-radius: 4px;
              overflow: hidden;
              border: 1px solid #d4d4d4;
              .bj-icon {
                .flex();
                align-items: center;
                padding: 0 6px;
                cursor: pointer;
              }
              .ant-input {
                flex: 1;
                height: 100%;
                line-height: 36px;
                border: none;
                padding: 0 10px;
                box-shadow: none !important;
              }
            }
          }
          .filter-result {
            flex: 1;
            .custom-scrollbar();
          }
        }
        .organization {
          border-right: 1px solid #d4d7d8;
        }
        .people {
          width: 300px;
          .filter-result {
            padding: 0 10px;
            label {
              display: block;
              margin-bottom: 12px;
            }
          }
        }
      }
      .no-choose-container {
        height: 100%;
        flex: 1;
        .flex();
        flex-direction: column;
        border: 1px solid #d4d7d8;
        border-radius: 4px;
        overflow: hidden;
        .ant-tree {
          li {
            width: 100%;
            .ant-tree-node-content-wrapper {
              width: calc(100% - 60px);
            }
          }
        }
      }
      .transfer-button {
        height: 100%;
        width: 70px;
        .flex();
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        .button {
          width: 46px;
          height: 28px;
          cursor: pointer;
          border-radius: 4px;
          background: var(--primary-color)
            url("https://jszhgd.cn/static/pc/transfer.png") no-repeat center
            center;
          background-size: 14px 10px;
          &.dis {
            background-color: #dcdcdc;
            cursor: not-allowed;
            &:active {
              opacity: 1;
            }
          }
        }
      }
      .choose-container {
        height: 100%;
        width: 300px;
        box-sizing: border-box;
        border: 1px solid #d4d7d8;
        border-radius: 4px;
        flex-shrink: 0;
        .flex();
        flex-direction: column;
        overflow: hidden;
        .transfer-container {
          padding: 10px 10px 0 0;
          .custom-scrollbar();
          .choosed-people {
            float: left;
            min-width: 84px;
            height: 32px;
            background: #f1f2f7;
            border-radius: 4px;
            .flex();
            align-items: center;
            box-sizing: border-box;
            padding: 0 10px;
            color: var(--primary-color);
            margin: 0 0 10px 10px;
            .flex();
            justify-content: space-between;
            .colose {
              width: 12px;
              height: 12px;
              background: var(--primary-color);
              border-radius: 50%;
              .flex();
              align-items: center;
              justify-content: center;
              color: #fff;
              cursor: pointer;
              margin-left: 4px;
              /deep/.bj-icon {
                transform: scale(0.6) translateY(1px);
              }
            }
          }
        }
      }
    }
    .modal-footer {
      justify-content: center;
    }
  }
}
</style>
